import { createRouter, createWebHistory, type Router, RouteRecordRaw } from "vue-router"
import { ROUTER_ROOT_PATH } from "./constant"
import { basicRoutes } from "./routes/basic"
import { cloneDeep } from "lodash-es"

export class BuildRoutes {

    static WHITE_ROUTE_NAME_LIST: string[] = []

    static ASYNC_ROUTERS_LIST: AppRouteRecord[] = []

    static ROUTER: Router;

    static init() {

        if (!this.ROUTER) {
            this.buildWhiteRoutes()
            this.buildAsyncRoutes()
            this.start()
        }
    }

    static start() {
        this.buildRouter()
    }

    //构建白名单路由列表
    static buildWhiteRoutes() {
        const whiteListPushHandle = (array: AppRouteRecord[]) => {
            array.forEach(route => {
                route.name && this.WHITE_ROUTE_NAME_LIST.push(route.name)
                whiteListPushHandle(route.children || [])
            })
        }
        whiteListPushHandle(basicRoutes)

    }

    //构建异步路由列表
    static buildAsyncRoutes() {
        const modules = import.meta.glob('./routes/modules/**/*.ts', { eager: true })
        Object.keys(modules).forEach(key => {
            let routes = (modules[key] as any).default || {}
            this.ASYNC_ROUTERS_LIST.push(cloneDeep(routes))
        })
    }

    //初始化路由
    static buildRouter() {
        try {
            !this.ROUTER && (
                this.ROUTER = createRouter({
                    history: createWebHistory(ROUTER_ROOT_PATH),
                    routes: basicRoutes as unknown as RouteRecordRaw[],
                    //严格检查路径末尾是否有尾部斜线,就是说/users不能匹配到/users/
                    strict: true,
                })
            )
        } catch (err) {
            throw new Error('初始化路由失败')
        }
    }

}

BuildRoutes.init()

export const router: Router = BuildRoutes.ROUTER